<template>
  <div class="warpper-box">
    <div class="inner_box">
     <form-create 
     v-model="params.fApi" 
     :rule="params.rule" 
     :option="params.option" 
     @btn-search-click="loadList(true)" 
     @btn-add-click="add(true)" 
     @btn-del-batch-click="delBatch"
     @btn-upload-click="uploadXlsx"
     @btn-reset-click="reset"/>
    <system-list
     :key="keys"
     :tableData="tables.tableData" 
     :tableLabel="tables.tableLabel" 
     :models="tables" 
     @on-search-click="loadList"
     @on-selection-click="selectionChange"
     @on-edit-click="add"
     @on-del-click="del"
     @on-resetPwd-click="resetPwd"
     @on-enable-click="onEnable"
     />
     <el-dialog :title="form.title" :visible.sync="form.visible" :width="form.width" :close-on-click-modal="false">
      <form-create 
      v-model="form.fApi" 
      :rule="form.rule" 
      :option="form.option" />

      <el-form :model="ruleForm">
        <el-form-item label="所属部门" prop="name">
          <el-cascader
          style="width:100%"
          v-model="ruleForm.deptId"
          :options="ruleForm.options"
    clearable></el-cascader>
        </el-form-item>
      </el-form>
      <!--  :props="{ checkStrictly: true }" -->
      <div slot="footer" class="dialog-footer">
        <el-button size="small" @click="form.visible = false">取 消</el-button>
        <el-button size="small" type="primary" @click="onFormSubmit">保存</el-button>
      </div>
    </el-dialog>
    </div>

   

  </div>
</template>

<script>
import store from '@/store'
import { PARAMS_USER,FORM_USER,OPTION_INLINE,USER_LABEL,OPTION_BLOCK} from "./systemUser/system_form"
import SystemList from "./systemUser/system_list"
import { arrayFormat,loginMD5 } from "@/utils/index"
import { getUserList,addUserSave,delUser,delBatchUser,disableUser,enableUser,roleUser,resetPwdUser } from "@/api/system_api"
import { xlsx } from "@/utils/xlsx"
import moment from "moment";
export default {
  components:{
    SystemList
  },
  data() {
    return {
      keys:0,
      params:{
        fApi:{},
        rule:PARAMS_USER,
        option:OPTION_INLINE
      },
      tables:{
        total:0,
        width:'260',
        hackReset:true,
        fixed:false,
        tableData:[],
        tableLabel: USER_LABEL
      },
      ruleForm:{
        deptId:[],
        options:[]
      },
      form:{
        id:'',
        title:'新增',
        width:"900px",
        visible:false,
        fApi:{},
        rule:[],
        option:OPTION_BLOCK
      },
      page:{
        pageNum:1,
        pageSize:10,
      },
      selectItem:[]
    };
  },
  mounted() {
    this.params.fApi.setValue({"name":"","deptId":[],"statusFlag":"","phone":""});
    //搜索条件
    this.$nextTick(async()=>{
      const departmentList = await store.dispatch('user/getAllDepartmentSelect');
      this.params.fApi.updateRule('deptId', {
          props:{options: departmentList}
                }, true);
      //表单部门加载
      this.ruleForm.options = departmentList;
      this.params.fApi.hidden(false, 'deptId')
      this.params.fApi.hidden(false, 'add')
      this.params.fApi.hidden(false, 'statusFlag')
    });
    this.loadList(true);
  },
  methods: {
    async loadList(formData) {
      let params = {};
      let query = this.params.fApi.bind();
      params.name = query.name;
      params.phone = query.phone;
      params.deptId = query.deptId.length !== 0 ? query.deptId.pop():'';
      params.statusFlag = query.statusFlag;
      
      if(formData !== undefined && formData.type === 'page'){
        this.page.pageNum = formData.page;
        this.page.pageSize = formData.pageSize;
      }
      if(formData===true){
        this.page.pageNum = 1;
        this.keys++;
      }
      params.pageNum = this.page.pageNum;
      params.pageSize = this.page.pageSize;
      params.userType = '1'
      const { data } = await getUserList(params);
      let result = data?.list ?? []
      this.tables.tableData = result
      this.tables.tableData.forEach(v=>{
        v.edit = true;
        v.del = true;
        v.isSwitch = true;
        if (v.id === 162) {
          v.del = false;
        }
        v.resetPwd = true;
      })
      this.tables.total = data.total;
    },
    add(row){
      this.form.rule = FORM_USER;
      this.ruleForm.deptId = [];//清空部门
      this.$nextTick(async ()=>{
        const roleList = await store.dispatch('user/getAllRole');
        const _roleList = arrayFormat(roleList);
        const _roleResult = _roleList.filter(v=>v.value !== 52);
        const positionList = await store.dispatch('user/getAllPosition');
        const _positionList = arrayFormat(positionList);
      /*   const departmentList = await store.dispatch('user/getAllDepartmentSelect');
        this.form.fApi.updateRule('deptId', {
          props:{options: departmentList}
                }, true) */
        this.form.fApi.updateRule('roleIds', {
          options: _roleResult
        }, true)
        this.form.fApi.updateRule('positionId', {
          options: _positionList
        }, true)

        if(row === true){
          this.form.title = "新增";
          this.form.id = "";
          this.form.fApi.disabled(false, 'password');
          this.form.fApi.updateValidate('password',[{required:true}], true)
          this.form.fApi.hidden(false, 'password');
          this.form.fApi.disabled(false, 'account');
          this.form.fApi.disabled(false, 'roleIds');
          this.form.fApi.disabled(false, 'statusFlag');
          this.form.fApi.resetFields();
        }else{
          this.form.title = "编辑";
          this.form.id = row.id;
          this.ruleForm.deptId = row.deptId;
          this.form.fApi.disabled(true, 'password');
          this.form.fApi.updateValidate('password',[{required:false}], true)
          this.form.fApi.hidden(true, 'password');

          if(row.id === 162){
            this.form.fApi.disabled(true, 'account');
            this.form.fApi.disabled(true, 'roleIds');
            this.form.fApi.disabled(true, 'statusFlag');
          } else {
            this.form.fApi.disabled(false, 'account');
            this.form.fApi.disabled(false, 'roleIds');
            this.form.fApi.disabled(false, 'statusFlag');
          }
          
          this.form.fApi.setValue({
            "account":row.account,
            "password":"",
            "name":row.name,
            "roleIds":parseInt(row.roleIds),
           // "deptId":row.deptId,
            "positionId":row.positionId,
            "statusFlag":row.statusFlag,
            "phone":row.phone,
            "email":row.email
          })
        }
      })
      this.form.visible = true;
    },
    async onFormSubmit() {
      this.form.fApi.submit(async (formData, $f) => {
        try {
          let text = "新增成功";
          let params = {};
          if(this.form.id){
            params.id = this.form.id;
            text = "修改成功"
          }else{
            params.password = loginMD5(formData.password);
          }
          if(!this.ruleForm.deptId && this.ruleForm.deptId.length == 0){
            return this.$message.error('请选择部门！')
          }
          params.account = formData.account;
          params.name = formData.name;
          params.roleIds = formData.roleIds;
          params.positionId = formData.positionId;
          params.deptId = Array.isArray(this.ruleForm.deptId) ? this.ruleForm.deptId.pop() : this.ruleForm.deptId;
          params.statusFlag = formData.statusFlag;
          params.phone = formData.phone;
          params.email = formData.email;
          const req = await addUserSave(params);
          if(req.code === 200){
            this.$message.success(text);
            this.form.visible = false;
            this.loadList(true);
          }
        } catch (error) {
          this.$message.info(error);
        }
      })
    },
    del(row){
      this.$confirm("确认删除", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(async () => {
        await delUser(row.id);
        this.$message.success("删除成功");
        this.loadList();
      }).catch(() => {});
    },
    selectionChange(arr){
      this.selectItem = arr;
    },
    delBatch(){
      if(this.selectItem.length === 0){
            return this.$message.error("请勾选要导出的数据！");
        }
        this.$confirm("确认删除", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(async () => {
          let ids = [];
          this.selectItem.forEach(v=>{
            ids.push(v.id)
          })
          const req = await delBatchUser(ids);
          if(req.code === 200){
            this.$message.success("操作成功");
            this.loadList(true);
          }
        }).catch(() => {});
    },
    async onEnable(row){
      let text = row.statusFlag==='1' ?'禁用':'启用';
      let tips = row.statusFlag==='1' ?'禁用成功':'启用成功';
      this.$confirm("确认"+text+"", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(async () => {
        row.statusFlag === '1' ? await disableUser(row.id) : await enableUser(row.id);
        this.$message.success(tips);
        this.loadList();
      }).catch(() => {});
    },
    resetPwd(row){
      this.$confirm("确认重置账号 "+row.account+" 密码为 135!sys010 ", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(async () => {
        const pwd = "135!sys010" + process.env.VUE_APP_FILE_Name;
        let params = {
          id:row.id,
          pwd:loginMD5(pwd)
        }
        await resetPwdUser(params);
        this.$message.success('操作成功');
        this.loadList();
      }).catch(() => {});
    },
    reset(){
      this.params.fApi.resetFields();
      this.loadList(true);
    },
    uploadXlsx(){
        const that = this;
        this.$prompt('请输入导出数量', '提示', {
          confirmButtonText: '导出',
          cancelButtonText: '取消',
          closeOnClickModal:false,
          inputPlaceholder:'导出数量不能大于列表总条数',
          inputValue:that.tables.total,
          inputValidator:function(val){
            if(!val){
              return false;
            }
            if(val > that.tables.total){
              return false;
            }else{
              return true;
            }
          },
          inputErrorMessage: '导出数量有误'
        }).then(async({ value }) => {
          let params = {};
          params.pageNum = 1;
          params.pageSize = value;
          params.userType = '1'
          const {code,data} = await getUserList(params);
          if(code === 200){
            if(data.list && data.list.length > 1){
              let fields = {
                title0: "编号",
                title1: "登录账户",
                title2: "真实姓名",
                title3: "所属角色",
                title4: "所属部门",
                title5: "所属职位",
                title6: "账号状态",
                title7: "创建时间",
              };
              let arry = [];
              let i = 0;
              data.list.forEach(ele => {
                const createTime = moment(ele.createTime).format("YYYY-MM-DD");
                  i++;
                  arry.push({
                      title0: i,
                      title1: ele.account,
                      title2: ele.name,
                      title3: ele.roleNames && ele.roleNames.length >= 1 ? ele.roleNames[0].name:'',
                      title4: ele.deptName,
                      title5: ele.positionName,
                    title6: ele.statusFlag == '1' ? '启用' : '禁用',
                      title7: createTime
                  });
              });
               const manualWidthColumns = [
                { width: 10 },
                { width: 15 },
                { width: 15 },
                { width: 15 },
                { width: 15 },
                { width: 15 },
                 { width: 15 },
                { width: 20 }
              ];
              xlsx(arry, fields, manualWidthColumns,"用户列表");
            }
          }
        }).catch(() => {});
      }
  }
};
</script>
<style>
  .el-cascader--small{
    width: 100% !important;
  }
</style>